Date.prototype.Format = function(fmt)
{
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}


var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') {
   options = options || {};
   if (value === null) {
    value = '';
    options = $.extend({}, options);
    options.expires = -1;
   }
   var expires = '';
   if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
    var date;
    if (typeof options.expires == 'number') {
     date = new Date();
     date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    } else {
     date = options.expires;
    }
    expires = '; expires=' + date.toUTCString();
   }
   var path = options.path ? '; path=' + (options.path) : '';
   var domain = options.domain ? '; domain=' + (options.domain) : '';
   var secure = options.secure ? '; secure' : '';
   document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else {
   var cookieValue = null;
   if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
     var cookie = jQuery.trim(cookies[i]);
     if (cookie.substring(0, name.length + 1) == (name + '=')) {
      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
      break;
     }
    }
   }
   return cookieValue;
}
};

var EARTH_RADIUS = 6378137.0;

function getGPSDistance(lat1,lng1,lat2,lng2){
    var f = getRad((lat1 + lat2)/2);
    var g = getRad((lat1 - lat2)/2);
    var l = getRad((lng1 - lng2)/2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s,c,w,r,d,h1,h2;
    var a = EARTH_RADIUS;
    var fl = 1/298.257;

    sg = sg*sg;
    sl = sl*sl;
    sf = sf*sf;

    s = sg*(1-sl) + (1-sf)*sl;
    c = (1-sg)*(1-sl) + sf*sl;

    w = Math.atan(Math.sqrt(s/c));
    r = Math.sqrt(s*c)/w;
    d = 2*w*a;
    h1 = (3*r -1)/2/c;
    h2 = (3*r +1)/2/s;

    return Math.round(d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg))/100)/10;
}

function getRad(d){
  return d*Math.PI/180.0;
}


var geolocation = function(address,cb){
    var MSearch;
    AMap.service(["AMap.PlaceSearch"], function() {
        MSearch = new AMap.PlaceSearch({ //构造地点查询类
            pageSize:10,
            pageIndex:1,
            city:"021" //城市
        });
        //关键字查询
        MSearch.search(address, function(status, result){
        	if(status === 'complete' && result.info === 'OK'){
        		cb(result);
        	}
        });
    });

}

jQuery.ajaxPrefilter(function( options ) {
    options.global =true;
});

var WXCONFIG={}

var API={
  wxConfig:function(){
    $.get("/api/wechat/sign",{url:location.origin+location.pathname+location.search},function(data){
        data.jsApiList=['scanQRCode','getLocation','chooseWXPay','showOptionMenu','showMenuItems']
        data.debug=true;
        WXCONFIG=data;
        wx.config(WXCONFIG);
        wx.ready(function(){
          console.log('wx ready');
          wx.isReady=true;
        });

        wx.error(function(res){
          console.log(res);
        });
    })
  },
  wxShare:function(){
    //wx.showMenuItems({menuList:["menuItem:share:appMessage","menuItem:share:timeline","menuItem:share:qq","menuItem:share:weiboApp"]});
    wx.showOptionMenu();
  },
  wxScanQRCode:function(oCall){
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
            var result = res.resultStr;
            oCall(result);
        },
        fail:function(res){
          console.log(res);
        }
    });
  },
  wxLocation:function(oCall){
    if(!wx.isReady){
      oCall({lat: 31.1189,lng:121.581});
    }
    wx.getLocation({
        success: function (res) {
            //alert(JSON.stringify(res));
            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            var speed = res.speed; // 速度，以米/每秒计
            var accuracy = res.accuracy; // 位置精度
            mylocation={lat:latitude,lng:longitude}
            oCall(mylocation)
        },
        fail:function(res){
          console.log(res);
        }
    });
  },
  customerGet:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId,oCall);
  },
  customerLogin:function(oParam,oCall){
    $.post('/api/users/login',oParam,oCall);
  },
  customerBalance:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId+'/balance',oCall);
  },
  customerCart:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId+'/cart',oCall);
  },
  customerLinkedPartners:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId+'/partners',oCall);
  },
  customerLinkPartner:function(oParam,oCall){
    $.post('/api/customers/'+oParam.customerId+'/partners',oParam,oCall);
  },
  partnerLinkedCustomers:function(oParam,oCall){
    $.get('/api/public/partners/'+oParam.partnerId+'/members',oCall);
  },
  customerOrders:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId+'/orders',oCall);
  },
  customerOrdersWithProduct:function(oParam,oCall){
    $.get('/api/customers/'+oParam.customerId+'/orderswithprd',oCall);
  },
  customerCancelOrder:function(oParam,oCall){
    $.post('/api/customers/'+oParam.customerId+'/orders/'+oParam.orderId+'/cancel',oCall);
  },
  getProduct:function(oParam,oCall){
    $.get('/api/products/'+oParam.productId,oCall);
  },
  partnerGet:function(oParam,oCall){
    $.get('/api/partners/'+oParam.partnerId,oCall);
  },
  shopsOfPartner:function(oParam,oCall){
    $.get('/api/public/partners/'+oParam.partnerId+'/shops',oCall);
  },
  flowsOfPartner:function(oParam,oCall){
    $.get('/api/partners/'+oParam.partnerId+'/billflows?page='+oParam.page,oCall);
  },
  ordersOfPartner:function(oParam,oCall){
    $.get('/api/partners/'+oParam.partnerId+'/orders?page='+oParam.page,oCall);
  },
  invoicesOutList:function(oParam,oCall){
    $.get('/api/admin/invoices?page='+oParam.page,oCall);
  },
  promotionRulesOfPartner:function(oParam,oCall){
    $.get('/api/partners/'+oParam.partnerId+'/promotions?page='+oParam.page,oCall);
  },
  deletePromotionRulesOfPartner:function(oParam,oCall){
    $.ajax({
      url:'/api/partners/'+oParam.partnerId+'/promotions/'+oParam.id,
      success:oCall,
      dataType:'json',
      type:'DELETE'
    })
  }
}


